package com.goldplusgold.tradedelay.app.home.live;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.live.LVDataManager;
import com.goldplusgold.live.bean.QuestionBean;
import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.support.lib.utils.Logger;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.tradedelay.app.home.live.base.LiveBaseCallBack;
import com.goldplusgold.tradedelay.app.home.live.fragment.AnswerFragment;
import com.goldplusgold.tradedelay.app.home.live.fragment.EssenceFragment;
import com.goldplusgold.tradedelay.app.home.adapter.FragmentAdapter;
import com.goldplusgold.tradedelay.app.home.live.fragment.TextLiveFragment;
import com.example.account.manager.ParmasKey;
import com.goldplusgold.tradedelay.app.main.activity.TDMainActivity;
import com.tb.emoji.Emoji;
import com.tb.emoji.FaceFragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/7/17.
 */

public class LiveDetailDownControler implements AnswerFragment.ChangeTabInterface, FaceFragment.OnEmojiClickListener,TabLayout.OnTabSelectedListener{

    private Context mContext;
    TabLayout mTabLayout;
    ViewPager mViewPager;
    int type;
    String liveID;
    String roomID;
    int liveStatus ;
    LinearLayout my_questions_bottom_layout;
    EditText editText;
    TextView send;
    TextView switchBtn;
    FaceFragment faceFragment;
    int emojiBoardState = 0;
    int questionState = 0;
    InputMethodManager imm;
    AnswerFragment answerFragment;
    EssenceFragment essenceFragment;
    TextLiveFragment liveFragment;
    public LiveDetailDownControler(Context context, TabLayout mTabLayout, ViewPager mViewPager, int type, String liveID, LinearLayout my_questions_bottom_layout,String roomID , int liveStatus){
        this.mContext = context;
        this.mTabLayout = mTabLayout;
        this.mViewPager = mViewPager;
        this.roomID = roomID;
        this.type = type;
        this.liveID = liveID;
        this.liveStatus = liveStatus ;
        this.my_questions_bottom_layout = my_questions_bottom_layout;
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
    }

    private void showEmoji(){
        if(emojiBoardState ==0){
            emojiBoardState =1;
            hideSoftInput();
            switchBtn.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(faceFragment == null){
                        faceFragment = FaceFragment.Instance();
                        faceFragment.setListener(LiveDetailDownControler.this);
                        ((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().add(R.id.emoji_container,faceFragment).commit();
                    } else {
                        ((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().show(faceFragment).commit();
                    }
                }
            },300);
            switchBtn.setBackgroundResource(R.drawable.edit_icon_keyboard);
        } else{
            emojiBoardState = 0;
            if(faceFragment != null){
                ((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().hide(faceFragment).commit();
            }
            switchBtn.setBackgroundResource(R.drawable.edit_icon_expression);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }

    public float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }

    protected void initView() {
        final View activityRootView = ((Activity)mContext).findViewById(R.id.activityRoot);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > dpToPx(mContext, 150)) {
                    // 显示软键盘
                    hideEmoji();
                }
            }
        });
        switchBtn = (TextView)my_questions_bottom_layout.findViewById(R.id.my_questions_swith_btn) ;
        switchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showEmoji();
            }
        });
        send = (TextView)my_questions_bottom_layout.findViewById(R.id.my_questions_send_btn);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                putMessage();
            }
        });
        editText = (EditText)my_questions_bottom_layout.findViewById(R.id.my_questions_edit);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.length() > 150){
                    editText.setText(editable.subSequence(0,150));
                    Toast.makeText(mContext,"提问字数不超过150字",Toast.LENGTH_SHORT).show();
                }
            }
        });
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                setWidth();
            }
        });
        answerFragment = new AnswerFragment(mContext,liveID,this,type);
        if(type == LiveDetailActivity.LiveDetailType.LIVE || type == LiveDetailActivity.LiveDetailType.TEXT_LIVE || type == LiveDetailActivity.LiveDetailType.VIDEO_LIVE){
            List<String> titles = new ArrayList<>();
            titles.add(mContext.getResources().getString(R.string.live_text));
            titles.add(mContext.getResources().getString(R.string.answer_text));
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(0)));
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(1)));
            List<Fragment> fragments = new ArrayList<>();
            liveFragment = new TextLiveFragment(roomID , liveStatus);
            fragments.add(liveFragment);
            fragments.add(answerFragment);
            FragmentAdapter adapter =
                    new FragmentAdapter(((AppCompatActivity)mContext).getSupportFragmentManager(), fragments, titles);
            mViewPager.setAdapter(adapter);
            mTabLayout.setupWithViewPager(mViewPager);
            mTabLayout.setTabsFromPagerAdapter(adapter);
            mTabLayout.addOnTabSelectedListener(this);
        } else {
            essenceFragment = new EssenceFragment();
            List<String> titles = new ArrayList<>();
            titles.add(mContext.getResources().getString(R.string.essence_text));
            titles.add(mContext.getResources().getString(R.string.answer_text));
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(0)));
            mTabLayout.addTab(mTabLayout.newTab().setText(titles.get(1)));
            List<Fragment> fragments = new ArrayList<>();
            fragments.add(essenceFragment);
            fragments.add(answerFragment);
            FragmentAdapter adapter =
                    new FragmentAdapter(((AppCompatActivity)mContext).getSupportFragmentManager(), fragments, titles);
            mViewPager.setAdapter(adapter);
            mTabLayout.setupWithViewPager(mViewPager);
            mTabLayout.setTabsFromPagerAdapter(adapter);
            mTabLayout.addOnTabSelectedListener(this);
        }
    }


    public void setEssence(String essence){
        if(essenceFragment != null){
            essenceFragment.setEssence(essence);
        }
    }

    private void hideEmoji(){
        if(faceFragment != null){
            ((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().hide(faceFragment).commit();
        }
    }

    private void putMessage(){
        if(type == LiveDetailActivity.LiveDetailType.LIVE ||type == LiveDetailActivity.LiveDetailType.VIDEO_LIVE || type == LiveDetailActivity.LiveDetailType.TEXT_LIVE){
            LVDataManager.getInstance().putLiveQuestion(liveID, editText.getEditableText().toString(), new LiveBaseCallBack<QuestionBean>(mContext) {
                @Override
                public void onResponse(Call<QuestionBean> call, Response<QuestionBean> response) {
                    super.onResponse(call , response);
                    if(response.body().getStatus()){
                        successReset();
                        if(answerFragment != null){
                            answerFragment.requestQuestions(1);
                        }
                    }
                    else{
                        Toast.makeText(mContext, "发送失败", Toast.LENGTH_SHORT).show();
                    }

                }
                @Override
                public void onFailure(Call<QuestionBean> call, Throwable t) {
                    super.onFailure(call , t);
                    successReset();
                    Logger.e("err","adfadfasdfa");
                }
            });
        } else {
            LVDataManager.getInstance().putVideoQuestion(liveID, editText.getEditableText().toString(), new LiveBaseCallBack<QuestionBean>(mContext) {
                @Override
                public void onResponse(Call<QuestionBean> call, Response<QuestionBean> response) {
                    super.onResponse(call , response);
                    if(response.body().getStatus()){
                        successReset();
                        if(answerFragment != null){
                            answerFragment.requestQuestions(1);
                        }
                    }else{
                        Toast.makeText(mContext, "发送失败", Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onFailure(Call<QuestionBean> call, Throwable t) {
                    super.onFailure(call , t);
                    successReset();
                    Logger.e("err","adfadfasdfa");
                }
            });
        }

    }

    private void successReset(){
        ((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                editText.setText("");
                hideEmoji();
                hideSoftInput();
            }
        });
    }

    private void setWidth(){
        try {
            //拿到tabLayout的mTabStrip属性
            Field mTabStripField = mTabLayout.getClass().getDeclaredField("mTabStrip");
            mTabStripField.setAccessible(true);

            LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(mTabLayout);
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                View tabView = mTabStrip.getChildAt(i);

                //拿到tabView的mTextView属性
                Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                mTextViewField.setAccessible(true);

                TextView mTextView = (TextView) mTextViewField.get(tabView);

                tabView.setPadding(0, 0, 0, 0);

                //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                int width = 0;
                width = mTextView.getWidth();
                if (width == 0) {
                    mTextView.measure(0, 0);
                    width = mTextView.getMeasuredWidth();
                }
                //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                int margin = width *2;
                params.width = width ;
                params.leftMargin = margin;
                params.rightMargin = margin;
                tabView.setLayoutParams(params);
                tabView.invalidate();
            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTab(int id) {
        if(AppCacheSharedPreferences.getCacheBoolean(ParmasKey.login_state , false)){
            questionState = id;
            if(id == 0){
                my_questions_bottom_layout.setVisibility(View.GONE);
            } else
                my_questions_bottom_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onEmojiDelete() {
        String text = editText.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                editText.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                displayTextView();
                return;
            }
            editText.getText().delete(index, text.length());
            displayTextView();
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        editText.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        displayTextView();
    }

    private void displayTextView() {
//        try {
//            EmojiUtil.handlerEmojiText(textView, editText.getText().toString(), this);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = editText.getSelectionStart();
            Editable editable = editText.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
        }
        displayTextView();
    }

    private void hideSoftInput(){
        imm.showSoftInput(editText,InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if(tab.getPosition() == 0){
            my_questions_bottom_layout.setVisibility(View.GONE);
            hideSoftInput();
        }else{
            if(emojiBoardState == 1){
                if(faceFragment != null){
                    ((AppCompatActivity)mContext).getSupportFragmentManager().beginTransaction().show(faceFragment).commit();
                }
            }
            if(questionState == 1){
                onTab(tab.getPosition());
            }
        }

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public void onDestory(){
        if(liveFragment != null){
            liveFragment.onDestroy();
        }
    }
}
